package com.pt5.pthouduan.util;


import com.pt5.pthouduan.entity.Torrent;
import com.turn.ttorrent.bcodec.BDecoder;
import com.turn.ttorrent.bcodec.BEValue;
import com.turn.ttorrent.bcodec.BEncoder;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.util.Map;

public class TorrentParser {
public static Torrent parse(byte[] torrentBytes) throws Exception {
    InputStream in = new ByteArrayInputStream(torrentBytes);
    BEValue decoded = BDecoder.bdecode(in);
    Map<String, BEValue> torrentMap = decoded.getMap();
    BEValue infoValue = torrentMap.get("info");
    if (infoValue == null) {
        throw new IllegalArgumentException("Invalid torrent file: missing 'info' dictionary");
    }

    // 提取 info 的 Map 并编码
    Map<String, BEValue> infoMap = infoValue.getMap();
    ByteBuffer buffer = BEncoder.bencode(infoMap);  // 返回 ByteBuffer
    byte[] infoBencoded = new byte[buffer.remaining()];
    buffer.get(infoBencoded);  // 转换为 byte[]

    // 计算 SHA-1 hash
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    byte[] hashBytes = digest.digest(infoBencoded);
    StringBuilder sb = new StringBuilder();
    for (byte b : hashBytes) {
        sb.append(String.format("%02x", b));
    }
    String infoHash = sb.toString();

    // 计算种子大小
    long torrentSize = 0;
    BEValue lengthValue = infoMap.get("length");
    if (lengthValue != null) {
        torrentSize = lengthValue.getLong();
    } else {
        BEValue filesValue = infoMap.get("files");
        if (filesValue != null) {
            for (BEValue fileValue : filesValue.getList()) {
                BEValue fileLength = fileValue.getMap().get("length");
                if (fileLength != null) {
                    torrentSize += fileLength.getLong();
                }
            }
        }
    }

    Torrent torrent = new Torrent();
    torrent.setInfoHash(infoHash);
    torrent.setTorrentSize(torrentSize);
    return torrent;
}
}
